package mscloud.config;

import cn.hutool.core.util.StrUtil;
import mscloud.service.CaptchaGenerationStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @Datetime: 2025年07月24日09:56
 * @Author: Eleven52AC
 * @Description: 验证码策略上下文
 */
@Component
public class CaptchaStrategyContext {

    private final Map<String, CaptchaGenerationStrategy> strategyMap;

    @Autowired
    public CaptchaStrategyContext(Map<String, CaptchaGenerationStrategy> strategyMap) {
        this.strategyMap = strategyMap;
    }

    public CaptchaGenerationStrategy getStrategy(String type) {
        if (StrUtil.isBlank(type)){
            type = "math";
        }
        String typeLower = type.toLowerCase();
        Optional<Map.Entry<String, CaptchaGenerationStrategy>> matched = strategyMap.entrySet()
                .stream()
                .filter(entry -> entry.getKey().toLowerCase().contains(typeLower))
                .findFirst();

        if (matched.isPresent()) {
            return matched.get().getValue();
        }
        throw new IllegalArgumentException("No captcha strategy found for type: " + type);
    }
}
